import { renderToString } from 'vue/server-renderer'
import { createApp } from './main'

export async function render(url: string) {
  const { app, router, pinia } = createApp()
  
  await router.push(url)
  await router.isReady()
  
  const ctx = {}
  const html = await renderToString(app, ctx)
  
  // 获取预加载资源
  const preloadLinks = renderPreloadLinks(ctx.modules)
  
  // 获取 Pinia 状态
  const piniaState = JSON.stringify(pinia.state.value)
  
  return [html, preloadLinks, piniaState]
}

function renderPreloadLinks(modules: Set<string>) {
  let links = ''
  const seen = new Set()
  
  modules.forEach(id => {
    const files = manifest[id]
    if (files) {
      files.forEach(file => {
        if (!seen.has(file)) {
          seen.add(file)
          links += renderPreloadLink(file)
        }
      })
    }
  })
  
  return links
}